package triStorage;

import java.io.*;

//
public class TriDiskFile {
	
	private RandomAccessFile rafile;
	
	private Object accessLock = new Object();
	
	public final String FileName;
	
	public TriDiskFile(String filename) {
		FileName = filename;
	}
	
	//return true if file is newly-created, false otherwise
	public boolean open() {
		try {
			File file = new File(FileName);
			if (!file.exists()) {
				System.out.println(FileName);
				file.createNewFile();
				rafile = new RandomAccessFile(file, "rw");
			
				return true;
			}
			else {
				rafile = new RandomAccessFile(file, "rw");
				return false;
			}
		}
		catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public long getFileLength() {
		synchronized (accessLock) {
			long len = -1;
			try {
				len = rafile.length();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			return len;
		}
	}
	
	public boolean read(long offset, byte[] buffer, int start, int length) {
		synchronized (accessLock) {
			try {
				rafile.seek(offset);
				rafile.read(buffer, start, length);
			}
			catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}
	}
	
	public boolean write(long offset, byte[] buffer, int start, int length) {
		synchronized (accessLock) {
			try {
				rafile.seek(offset);
				rafile.write(buffer, start, length);
			}
			catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			
			return true;
		}
	}
	
	public void close() {
		synchronized (accessLock) {
			try {
				rafile.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
